type RequestOptions = RequestInit & {
  baseUrl?: string;
};

export async function request<T>(
  url: string,
  options: RequestOptions = {}
): Promise<T | null> {
  const { baseUrl = process.env.NEXT_PUBLIC_REQUEST_URL, ...resOptions } =
    options;
  try {
    const response = await fetch(baseUrl + url, resOptions);
    if (!response.ok) {
      let errorText: string;
      try {
        const errJson = await response.json();
        errorText = errJson.message || errJson.msg || JSON.stringify(errJson);
      } catch {
        errorText = await response.text();
      }
      console.error(`HTTP ${response.status}: ${errorText || "未知错误"}`);
      return null;
    }
    // 解析后端统一格式
    const result = await response.json();
    if (result.code !== 0) {
      console.error(result.msg || "业务错误");
      return null;
    }
    return result;
  } catch (error) {
    // 处理 fetch 本身抛出的错误（网络问题 / CORS / DNS）
    console.error(error instanceof Error ? error.message : "网络异常");
    return null;
  }
}
